package org.itheima.controller;

import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.itheima.pojo.Result;
import org.itheima.pojo.User;
import org.itheima.service.UserService;
import org.itheima.utils.JwtUtil;
import org.itheima.utils.Md5Util;
import org.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired//导入方法
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //注册逻辑
    @PostMapping("/register")//作用是发送请求
    public Result register(@Pattern(regexp = "^\\S{3,12}$") String username,@Pattern(regexp = "^\\S{3,12}$") String password) {

            //查询用户，判断是否用户已经存在
            User user = userService.findByUserName(username);
            if (user == null) {
                //没有占用,进行注册
                userService.register(username,password);
                return Result.success();
            }else {
                //用户被占用
                return Result.error("用户已经被占用");
            }
        }


    //登录逻辑
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{3,12}$") String username,@Pattern(regexp = "^\\S{3,12}$") String password) {
        User loginUser = userService.findByUserName(username);

        //判断用户是否存在
        if (loginUser == null){
            return Result.success("用户名错误");
        }

        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("Id",loginUser.getId());
            claims.put("userName",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);

            //把token存储到redis中
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }


    //用户信息获取
    @PostMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //根据用户名查询用户
        //Map<String,Object> map = JwtUtil.parseToken(token);
        //String username = (String) map.get("userName");
        Map<String,Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("userName");
        User user = userService.findByUserName(userName);
        return Result.success(user);
    }

    /// 更新用户数据
    @PostMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success("更新成功");
    }

    //更新头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success("头像更新成功");
    }
    /*
     * userService：接口
     * updateAvatar新的方法名，每次需要新建，在userService里面
     * */

    //更新密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token) {
        //1、校验参数,创建三个密码对象进行校验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //验证是否填写
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //调用userservice根据用户名拿到原密码，在和oldpwd对比
        Map<String,Object> map = ThreadLocalUtil.get();//根据用户名进行查找密码
        String userName = (String) map.get("userName");
        User loginUser = userService.findByUserName(userName);
        //注意这里传输过来的密码是加密的密码
        //判断密码原密码是否正确
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }
        //判断第二次输入的新密码是否匹配
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写的密码不一样");
        }
        //2、调用service响应数据
        userService.updatePwd(newPwd);
        //密码更新后需要，删除redis中对应的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);

        return Result.success("密码修改成功");
    }
}
